﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using BLL;
using Common;
using Web.Extension;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Web.Controllers;
using Microsoft.AspNetCore.Authorization;
using Web.Filter;
namespace Web.Users.Controllers
{   
   /// <summary>
   /// 图片资源接口
   /// </summary>
    public class ImageController :  MyApiBaseController<Image>
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        public ImageController(IImageBll bll, IWebHostEnvironment webHostEnvironment) : base(bll)
        {
            this.webHostEnvironment = webHostEnvironment;
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id">id值，单个值如：1</param>
        /// <param name="where">不能传递其他条件，目前只能根据id删除单个</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public override async Task<Result<object>> Delete(string id,[FromQuery] Dictionary<string, string> where)
        {
            var idInt = int.Parse(id.Split(",")[0]);
            var obj = bll.SelectOne(idInt);
            string filePath = webHostEnvironment.WebRootPath + obj.Path;
            System.IO.File.Delete(filePath);
            return await bll.DeleteAsync(where) ? Result<object>.Success("删除成功") : Result<object>.Error("删除失败");
        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<Result<object>> Upload(IFormFile file)
        {
            var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (string.IsNullOrEmpty(ext) || !ImgExt.Contains(ext))
            {
                return Result<object>.Error("上传失败,请选择jpg|jpeg|png|gif类型图片");
            }
            if (file.Length > 0)
            {
                if (file.Length > ImgSizeLimit)
                {
                    var size = ImgSizeLimit / 1024;
                    return Result<object>.Error($"上传失败,文件超过大小{size}KB");
                }
                //汉字转拼音
                //string filename = Pinyin4Net.GetPinyin(file.FileName, PinyinFormat.LOWERCASE);
                string filePath = "/upload/" + Guid.NewGuid().ToString() + ext;
                //string phypath= webHostEnvironment.WebRootPath + filePath;
                //if (System.IO.File.Exists(phypath))
                // {
                //     Guid.NewGuid().ToString()
                // }
                Image o = new Image
                {
                    Name = file.FileName
                };

                o.UserId = MyUser.Id;

                //是否是系统上传
                if (MyUser.Role.StartsWith("admin") || MyUser.Role.StartsWith("school"))
                {
                    o.Sys = true;
                }
                else
                {
                    o.Sys = false;
                }
                o.Path = filePath;
                using (var stream = System.IO.File.Create(webHostEnvironment.WebRootPath + filePath))
                {
                    await file.CopyToAsync(stream);
                }
                bll.Add(o);
                return Result<object>.Success("上传成功").SetData(o);
            }
            else
            {
                return Result<object>.Success("上传失败,空文件");
            }
        }
    }
}
